<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use app\admin\model\ProductAttributePrice;

/**
 * 积分商品管理
 * @icon fa fa-star
 * @remark 积分商品列表管理
 */
class ProductPoints extends Backend
{
    protected $model = null;
    protected $searchFields = ['price'];
    protected $relationSearch = true;
    
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new ProductAttributePrice();
    }
    
    /**
     * 积分商品列表
     */
    public function index()
    {
        // 设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        
        if ($this->request->isAjax()) {
            // 如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            
            try {
                // 获取请求参数
                $page = $this->request->get('page', 1);
                $limit = $this->request->get('limit', 10);
                $search = $this->request->get('search', '');
                
                // 计算偏移量
                $offset = ($page - 1) * $limit;
                
                // 构建查询条件
                $where = ['attribute_type' => 2];
                
                // 先获取不重复的商品ID列表（按最新记录排序）
                $subQueryBuilder = Db::name('product_attribute_price')
                    ->alias('pap')
                    ->where($where)
                    ->field('pap.product_id, MAX(pap.id) as max_id');
                
                // 如果有搜索条件，添加商品名称搜索
                if (!empty($search)) {
                    $subQueryBuilder->join('product p', 'pap.product_id = p.id')
                        ->where('p.name', 'like', '%' . $search . '%');
                }
                
                $subQuery = $subQueryBuilder->group('pap.product_id')->buildSql();
                
                $productIds = Db::table($subQuery . ' a')
                    ->order('max_id', 'desc')
                    ->limit($offset, $limit)
                    ->column('product_id');
                
                // 获取总数（按商品分组计算）
                $total = Db::name('product_attribute_price')
                    ->where($where)
                    ->group('product_id')
                    ->count();
                
                $list = [];
                if (!empty($productIds)) {
                    // 根据商品ID获取详细信息
                    foreach ($productIds as $productId) {
                        // 获取该商品的第一条积分记录
                        $points = Db::name('product_attribute_price')
                            ->where('product_id', $productId)
                            ->where('attribute_type', 2)
                            ->order('id', 'asc')
                            ->find();
                        
                        if ($points) {
                            // 获取商品信息
                            $product = Db::name('product')
                                ->alias('p')
                                ->join('product_category pc', 'p.category_id = pc.id', 'LEFT')
                                ->join('merchant_audit ma', 'p.merchant_id = ma.merchant_id', 'LEFT')
                                ->field('p.*, pc.name as category_name, ma.store_name as merchant_name')
                                ->where('p.id', $productId)
                                ->find();
                            
                            if ($product) {
                                $list[] = [
                                    'id' => $points['id'],
                                    'product_id' => $productId,
                                    'product_name' => $product['name'],
                                    'category_name' => $product['category_name'] ?: '未分类',
                                    'merchant_name' => $product['merchant_name'] ?: $product['merchant_id'],
                                    'sales' => $product['sales'] ?? 0,
                                    'stock' => $product['stock'] ?? 0,
                                    'points' => $points['points'],
                                    'original_price' => $product['price'] ?? 0,
                                    'status' => $points['status'],
                                    'createtime' => $points['createtime'],
                                    'updatetime' => $points['updatetime']
                                ];
                            }
                        }
                    }
                }
                
                // 处理默认值
                foreach ($list as &$item) {
                    $item['category_name'] = $item['category_name'] ?: '未分类';
                    $item['sales'] = $item['sales'] ?? 0;
                    $item['stock'] = $item['stock'] ?? 0;
                    $item['original_price'] = $item['original_price'] ?? 0;
                    $item['points'] = $item['points'] ?? 0;
                }
                
                // 如果有搜索条件，重新计算总数
                if (!empty($search)) {
                    $searchTotal = Db::name('product_attribute_price')
                        ->alias('pap')
                        ->join('product p', 'pap.product_id = p.id')
                        ->where($where)
                        ->where('p.name', 'like', '%' . $search . '%')
                        ->group('pap.product_id')
                        ->count('DISTINCT pap.product_id');
                    $total = $searchTotal;
                }
                
                // 处理数据格式
                 foreach ($list as &$item) {
                     // 格式化时间
                     $item['createtime'] = date('Y-m-d H:i:s', $item['createtime']);
                     $item['updatetime'] = date('Y-m-d H:i:s', $item['updatetime']);
                     
                     // 格式化积分商品状态
                     $item['status_text'] = $item['status'] == 1 ? '上架' : '下架';
                     
                     // 格式化价格
                     $item['original_price'] = number_format($item['original_price'], 2);
                     
                     // 格式化销量和库存
                     $item['sales'] = intval($item['sales']);
                     $item['stock'] = intval($item['stock']);
                     $item['points'] = intval($item['points']);
                 }
                
                // 返回结果
                $result = array("total" => $total, "rows" => $list);
                return json($result);
                
            } catch (\Exception $e) {
                return json(['code' => 0, 'msg' => '获取积分商品数据失败: ' . $e->getMessage()]);
            }
        }
        
        return $this->view->fetch();
    }
    
    /**
     * 添加积分商品配置
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');
            if ($params) {
                // 验证商品ID
                if (empty($params['product_id'])) {
                    $this->error('请选择商品');
                }
                
                try {
                    // 检查是否提交了SKU积分数据
                    $skuPoints = $this->request->post('sku_points/a');
                    
                    if (!empty($skuPoints)) {
                        // 批量添加SKU积分配置
                        $insertCount = 0;
                        foreach ($skuPoints as $skuId => $points) {
                            if ($points > 0) {
                                // 检查该SKU是否已存在积分配置
                                $exists = Db::name('product_attribute_price')
                                    ->where('product_id', $params['product_id'])
                                    ->where('sku_id', $skuId)
                                    ->where('attribute_type', 2)
                                    ->find();
                                
                                if ($exists) {
                                    $this->error("SKU ID {$skuId} 已存在积分商品配置");
                                }
                                
                                // 插入新配置
                                $result = Db::name('product_attribute_price')->insert([
                                    'product_id' => $params['product_id'],
                                    'sku_id' => $skuId,
                                    'attribute_type' => 2,
                                    'price' => 0, // 积分商品价格固定为0
                                    'points' => isset($skuPoints[$skuId]) ? $skuPoints[$skuId] : 0,
                                    'status' => isset($params['shelf_status']) ? $params['shelf_status'] : 1,
                                    'createtime' => time(),
                                    'updatetime' => time()
                                ]);
                                
                                if ($result !== false) {
                                    $insertCount++;
                                }
                            }
                        }
                        
                        if ($insertCount > 0) {
                            $this->success('添加成功');
                        } else {
                            $this->error('没有添加任何数据');
                        }
                    } else {
                        // 单个商品积分配置
                        $singlePoints = $this->request->post('single_points');
                        
                        if (!$singlePoints) {
                            throw new Exception('请设置所需积分');
                        }
                        
                        // 检查该商品是否已存在积分商品配置
                        $exists = Db::name('product_attribute_price')
                            ->where('product_id', $params['product_id'])
                            ->where('attribute_type', 2)
                            ->find();
                        if ($exists) {
                            $this->error('该商品已存在积分商品配置');
                        }
                        
                        // 获取商品的默认SKU
                        $defaultSku = Db::name('product_sku')
                            ->where('product_id', $params['product_id'])
                            ->where('status', 1)
                            ->order('id', 'asc')
                            ->find();
                        
                        if (!$defaultSku) {
                            throw new Exception('该商品没有可用的SKU规格');
                        }
                        
                        // 插入积分商品配置
                        $data = [
                            'product_id' => $params['product_id'],
                            'sku_id' => $defaultSku['id'],
                            'attribute_type' => 2,
                            'price' => 0, // 积分商品价格固定为0
                            'points' => $singlePoints,
                            'status' => isset($params['shelf_status']) ? $params['shelf_status'] : 1,
                            'createtime' => time(),
                            'updatetime' => time()
                        ];
                        
                        $result = Db::name('product_attribute_price')->insert($data);
                        if ($result) {
                            $this->success('添加成功');
                        } else {
                            $this->error('添加失败');
                        }
                    }
                } catch (\think\exception\HttpResponseException $e) {
                    // FastAdmin的success/error方法会抛出HttpResponseException，这是正常的
                    throw $e;
                } catch (\Exception $e) {
                    $this->error('添加失败：' . $e->getMessage());
                }
            }
            $this->error('参数不能为空');
        }
        
        return $this->view->fetch();
    }
    
    /**
     * 编辑积分商品配置
     */
    public function edit($ids = null)
    {
        // 从product_attribute_price表获取数据
        $row = Db::name('product_attribute_price')
            ->alias('pap')
            ->join('product p', 'pap.product_id = p.id')
            ->field('pap.*, p.name as product_name')
            ->where('pap.id', $ids)
            ->where('pap.attribute_type', 2)
            ->find();
            
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');
            if ($params) {
                try {
                    // 检查是否提交了SKU积分数据
                    $skuPoints = $this->request->post('sku_points/a');
                    
                    if (!empty($skuPoints)) {
                        // 批量更新SKU积分
                        $updateCount = 0;
                        foreach ($skuPoints as $skuId => $points) {
                            if ($points !== '') {
                                // 检查该SKU是否已存在积分配置
                                $exists = Db::name('product_attribute_price')
                                    ->where('product_id', $row['product_id'])
                                    ->where('sku_id', $skuId)
                                    ->where('attribute_type', 2)
                                    ->find();
                                
                                if ($exists) {
                                    // 更新现有配置
                                    $result = Db::name('product_attribute_price')
                                        ->where('id', $exists['id'])
                                        ->update([
                                            'points' => $points,
                                            'status' => isset($params['shelf_status']) ? $params['shelf_status'] : 1,
                                            'updatetime' => time()
                                        ]);
                                    if ($result !== false) {
                                        $updateCount++;
                                    }
                                } else {
                                    // 新增配置
                                    $result = Db::name('product_attribute_price')->insert([
                                        'product_id' => $row['product_id'],
                                        'sku_id' => $skuId,
                                        'attribute_type' => 2,
                                        'price' => 0, // 价格设为0，因为我们只关心积分
                                        'points' => $points,
                                        'status' => isset($params['shelf_status']) ? $params['shelf_status'] : 1,
                                        'createtime' => time(),
                                        'updatetime' => time()
                                    ]);
                                    if ($result !== false) {
                                        $updateCount++;
                                    }
                                }
                            }
                        }
                        
                        if ($updateCount > 0) {
                            $this->success();
                        } else {
                            $this->error('没有更新任何数据');
                        }
                    } else {
                        // 原有的单个积分价格更新逻辑（兼容旧版本）
                        
                        // 验证所需积分
                        if (!isset($params['points']) || $params['points'] < 0) {
                            $this->error('请输入有效的所需积分');
                        }
                        
                        // 准备更新数据
                        $data = [
                            'points' => $params['points'],
                            'status' => isset($params['shelf_status']) ? $params['shelf_status'] : 1,
                            'updatetime' => time()
                        ];
                        
                        // 更新数据
                        $result = Db::name('product_attribute_price')
                            ->where('id', $ids)
                            ->where('attribute_type', 2)
                            ->update($data);
                        
                        if ($result !== false) {
                            $this->success();
                        } else {
                            $this->error('更新失败');
                        }
                    }
                } catch (\think\exception\HttpResponseException $e) {
                    // FastAdmin的success/error方法会抛出HttpResponseException，这是正常的
                    throw $e;
                } catch (\Exception $e) {
                    $this->error('更新失败：' . $e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        
        // 获取商品信息和规格信息
        $product = Db::name('product')
            ->alias('p')
            ->join('product_category pc', 'p.category_id = pc.id', 'LEFT')
            ->field('p.*, pc.name as category_name')
            ->where('p.id', $row['product_id'])
            ->find();
        
        // 获取商品的SKU规格
        $skus = Db::name('product_sku')
            ->where('product_id', $row['product_id'])
            ->where('status', 1)
            ->field('id, sku_name, price, original_price, stock, spec_value_ids')
            ->select();
        
        // 获取已存在的积分配置
        $existingPoints = Db::name('product_attribute_price')
            ->where('product_id', $row['product_id'])
            ->where('attribute_type', 2)
            ->column('points', 'sku_id');
        
        // 为每个SKU添加积分信息
        foreach ($skus as &$sku) {
            $sku['has_points'] = isset($existingPoints[$sku['id']]);
            $sku['points'] = $sku['has_points'] ? $existingPoints[$sku['id']] : '';
        }
        
        // 传递数据到视图
        $this->view->assign('product', $product);
        $this->view->assign('skus', $skus);
        $this->view->assign('row', $row);
        
        return $this->view->fetch();
    }
    
    /**
     * 删除积分商品配置
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            try {
                Db::startTrans();
                
                $idsArray = explode(',', $ids);
                $deletedProductIds = [];
                $totalCount = 0;
                
                // 遍历每个ID，获取对应的商品ID，然后删除该商品的所有积分记录
                foreach ($idsArray as $id) {
                    // 根据记录ID获取商品ID
                    $record = Db::name('product_attribute_price')
                        ->where('id', $id)
                        ->where('attribute_type', 2)
                        ->field('product_id')
                        ->find();
                    
                    if ($record && !in_array($record['product_id'], $deletedProductIds)) {
                        // 删除该商品的所有积分记录
                        $count = Db::name('product_attribute_price')
                            ->where('product_id', $record['product_id'])
                            ->where('attribute_type', 2)
                            ->delete();
                        
                        if ($count > 0) {
                            $deletedProductIds[] = $record['product_id'];
                            $totalCount += $count;
                        }
                    }
                }
                
                Db::commit();
                
                if ($totalCount > 0) {
                    $this->success("成功删除 " . count($deletedProductIds) . " 个商品的积分配置，共 {$totalCount} 条记录");
                } else {
                    $this->error(__('No rows were deleted'));
                }
            } catch (\think\exception\HttpResponseException $e) {
                Db::rollback();
                // FastAdmin的success/error方法会抛出HttpResponseException，这是正常的
                throw $e;
            } catch (\Exception $e) {
                Db::rollback();
                $this->error('删除失败：' . $e->getMessage());
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
    
    /**
     * 批量更新积分商品配置
     */
    public function multi($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $action = $this->request->post("action");
        
        if ($ids) {
            $idsArray = explode(',', $ids);
            
            try {
                Db::startTrans();
                
                $count = 0;
                switch ($action) {
                    case 'enable':
                        // 批量启用
                        $count = Db::name('product_attribute_price')
                            ->where('id', 'in', $idsArray)
                            ->where('attribute_type', 2)
                            ->update(['status' => 1, 'updatetime' => time()]);
                        break;
                    case 'disable':
                        // 批量禁用
                        $count = Db::name('product_attribute_price')
                            ->where('id', 'in', $idsArray)
                            ->where('attribute_type', 2)
                            ->update(['status' => 0, 'updatetime' => time()]);
                        break;
                    case 'delete':
                        // 批量删除 - 删除整个商品的所有积分记录
                        $deletedProductIds = [];
                        foreach ($idsArray as $id) {
                            // 根据记录ID获取商品ID
                            $record = Db::name('product_attribute_price')
                                ->where('id', $id)
                                ->where('attribute_type', 2)
                                ->field('product_id')
                                ->find();
                            
                            if ($record && !in_array($record['product_id'], $deletedProductIds)) {
                                // 删除该商品的所有积分记录
                                $deleteCount = Db::name('product_attribute_price')
                                    ->where('product_id', $record['product_id'])
                                    ->where('attribute_type', 2)
                                    ->delete();
                                
                                if ($deleteCount > 0) {
                                    $deletedProductIds[] = $record['product_id'];
                                    $count += $deleteCount;
                                }
                            }
                        }
                        break;
                    default:
                        $this->error('未知操作');
                }
                
                Db::commit();
                
                if ($count > 0) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            } catch (\think\exception\HttpResponseException $e) {
                Db::rollback();
                // FastAdmin的success/error方法会抛出HttpResponseException，这是正常的
                throw $e;
            } catch (\Exception $e) {
                Db::rollback();
                $this->error('操作失败：' . $e->getMessage());
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
    
    /**
     * 根据商品ID获取商品规格
     */
    public function getProductSkus()
    {
        $productId = $this->request->post('product_id');
        if (!$productId) {
            return json(['code' => 0, 'msg' => '商品ID不能为空']);
        }
        
        try {
            // 获取商品信息（关联分类表）
            $product = Db::name('product')
                ->alias('p')
                ->join('product_category pc', 'p.category_id = pc.id', 'LEFT')
                ->field('p.*, pc.name as category_name')
                ->where('p.id', $productId)
                ->find();
            if (!$product) {
                return json(['code' => 0, 'msg' => '商品不存在']);
            }
            
            // 检查商品审核状态
            if ($product['audit_status'] != 1) {
                $auditStatusText = '';
                switch ($product['audit_status']) {
                    case 0:
                        $auditStatusText = '审核中';
                        break;
                    case 2:
                        $auditStatusText = '审核未通过';
                        break;
                    default:
                        $auditStatusText = '审核状态异常';
                        break;
                }
                return json(['code' => 0, 'msg' => "该商品{$auditStatusText}，不可分配积分价格"]);
            }
            
            // 获取商品的SKU规格
            $skus = Db::name('product_sku')
                ->where('product_id', $productId)
                ->where('status', 1)
                ->field('id, sku_name, price, original_price, stock, spec_value_ids')
                ->select();
            
            if (empty($skus)) {
                return json(['code' => 0, 'msg' => '该商品暂无规格信息']);
            }
            
            // 检查是否已存在积分商品配置
            $existingPoints = Db::name('product_attribute_price')
                ->where('product_id', $productId)
                ->where('attribute_type', 2)
                ->column('sku_id');
            
            // 为每个SKU添加是否已配置的标识
            foreach ($skus as &$sku) {
                $sku['has_points'] = in_array($sku['id'], $existingPoints);
                $sku['points'] = '';
            }
            
            return json([
                'code' => 1,
                'msg' => '获取成功',
                'data' => [
                    'product' => $product,
                    'skus' => $skus
                ]
            ]);
            
        } catch (\Exception $e) {
            return json(['code' => 0, 'msg' => '获取商品规格失败：' . $e->getMessage()]);
        }
    }
}